<template>
	<div class="pageWrap bgc">
		<div class="aside-box-system">
			<el-aside width="200px" style="height: 100%">
				<el-container>
					<el-header>
						<el-input v-model="groupFilterText" placeholder="输入关键字进行过滤" clearable style="margin-top: 10px" />
					</el-header>
					<el-main class="nopadding">
						<el-tree
							ref="treeRef"
							class="menu-tree"
							:data="treeData"
							node-key="id"
							:current-node-key="''"
							:highlight-current="true"
							:expand-on-click-node="false"
							:props="defaultProps"
							default-expand-all
							:filter-node-method="filterNode"
							@node-click="roleClick"
						/>
					</el-main>
				</el-container>
			</el-aside>
		</div>
		<!--		<el-divider direction="vertical" style="height: 100%" />-->
		<div class="content-warp flex-column-page-wrap">
			<!-- 公用搜索组件 -->
			<LeSearchForm ref="searchForm" v-model:searchData="searchData" :forms="forms" :loading="tableOpts.options.loading"></LeSearchForm>

			<!--  LeTable 组件使用  -->
			<LeTable
				ref="tableRef"
				v-model:searchParams="tableOpts.searchParams"
				v-bind="tableOpts"
				v-model:curRow="tableOpts.curRow"
				v-model:checked-options="checkedColumns"
				:columns="activeColumns"
			>
				<template #toolLeft>
					<el-button type="primary" @click="addHandler">
						<el-icon class="btn-icon">
							<Plus />
						</el-icon>
					</el-button>
					<el-button type="danger" :disabled="curSelectionRows.length === 0" @click="batch_del">
						<el-icon class="btn-icon">
							<Delete />
						</el-icon>
					</el-button>
					<el-button plain :disabled="curSelectionRows.length === 0" @click="chooseThing('role')"> 分配角色</el-button>
					<el-button plain :disabled="curSelectionRows.length === 0" @click="chooseThing('department')"> 分配部门 </el-button>
					<el-button plain :disabled="curSelectionRows.length === 0" @click="resetPwdVisibile = true"> 密码重置 </el-button>
				</template>

				<template #filterAvatarSlot="scope">
					<el-avatar :src="scope.row.avatar" size="small"></el-avatar>
				</template>

				<template #statusSlot="scope">
					<status-indicator v-if="scope.row.status === 1" pulse type="success"></status-indicator>
					<status-indicator v-else pulse type="danger"></status-indicator>
				</template>

				<template #actionSlot="{ row }">
					<div class="flex flex-align-pack-center">
						<LeIcon class="text-lg text-icon-color cursor-pointer" icon-class="icon-processInfo-mage--edit" @click="table_edit(row)" />

						<LeIcon class="text-lg ml-2 text-rose-700 cursor-pointer" icon-class="icon-processInfo-iconoir--trash" @click="table_del(row)" />
					</div>
				</template>
			</LeTable>
		</div>

		<LeFormConfigDialog
			v-if="visible"
			ref="dialogUserRef"
			v-model="visible"
			:title="`${isCreate ? '新增' : '编辑'}用户`"
			width="600px"
			:form-data="activeData"
			:form-options="formOptions"
			@submit="submitHandler"
		/>

		<assign-role-dialog
			v-if="assignRoleVisibile"
			v-model="assignRoleVisibile"
			:user-ids="curSelectionRows.map(item => item.id)"
			:type-model="typeModel"
			@success-fn="updateParams()"
			@closed="assignRoleVisibile = false"
		></assign-role-dialog>

		<reset-pwd
			v-if="resetPwdVisibile"
			v-model="resetPwdVisibile"
			:user-ids="curSelectionRows.map(item => item.id)"
			@closed="resetPwdVisibile = false"
		>
		</reset-pwd>
	</div>
</template>
<script lang="tsx" setup>
import role from '@/api/system/role'
import user from '@/api/system/user'
import department from '@/api/system/department'
import { computed, nextTick, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, ElTree } from 'element-plus'
import { useTablePage } from '@/hooks/useTablePage'
import { Plus, Delete } from '@element-plus/icons-vue'
import StatusIndicator from '@/components/StatusIndicator'
import AssignRoleDialog from './assign-role.vue'
import ResetPwd from './reset-pwd.vue'

const visible = ref(false) // 弹窗显示隐藏
const isCreate = ref(true)
const activeData = ref({})
const formsDialog = [
	{
		prop: 'username',
		label: '登录账号',
		itemType: 'input',
		placeholder: '用于登录系统',
		rules: [{ required: true, message: '请输入登录账号', trigger: 'blur' }]
	},
	{
		prop: 'password',
		label: '登录密码',
		itemType: 'input',
		rules: [{ required: true, message: '请输入登录密码', trigger: 'blur' }]
	},
	{
		prop: 'password2',
		label: '确认密码',
		itemType: 'input',
		rules: [{ required: true, message: '请再次输入密码', trigger: 'blur' }]
	},
	{
		prop: 'nickName',
		label: '昵称',
		itemType: 'input'
	},
	{
		prop: 'realName',
		label: '姓名',
		itemType: 'input'
	},
	{
		prop: 'sex',
		label: '性别',
		itemType: 'radio',
		options: [
			{ value: '男', label: '男' },
			{ value: '女', label: '女' }
		]
	},
	{
		prop: 'status',
		label: '状态',
		itemType: 'switch',
		activeText: '正常',
		inactiveText: '禁用'
	},
	{
		prop: 'roleIds',
		label: '所属角色',
		itemType: 'select',
		multiple: true,
		collapseTags: true,
		maxCollapseTags: 1,
		filterable: true,
		options: []
	},
	{
		prop: 'departmentIds',
		label: '所属部门',
		itemType: 'select',
		multiple: true,
		collapseTags: true,
		maxCollapseTags: 1,
		filterable: true,
		options: []
	}
]
// 新增的表单 和 编辑的表单
const formOptions = computed(() => {
	// 去掉 formsDialog 下标为 1 2 的数据
	const { 1: password, 2: password2, ...rest } = formsDialog
	let editFormDialog = []
	for (let i in rest) {
		editFormDialog.push(rest[i])
	}
	return {
		forms: isCreate.value ? formsDialog : editFormDialog,
		labelWidth: 120,
		span: 30,
		formConfig: {
			showCancelBtn: true,
			submitLoading: false
		}
	}
})
const showGroupLoading = ref(false)
const assignRoleVisibile = ref(false)
const resetPwdVisibile = ref(false)
const groupFilterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()

const defaultProps = {
	children: 'children',
	label: 'label'
}

const filterNode = (value: string, data: Tree) => {
	if (!value) return true
	return data.label.includes(value)
}

const treeData = ref([])
const typeModel = ref('')

// 获取左侧菜单数据
const getGroup = async () => {
	showGroupLoading.value = true
	let data = await role.roleListTreeApi()
	showGroupLoading.value = false
	data.unshift({ id: '', label: '所有' })
	treeData.value = data // console.log('获取左侧菜单数据')
}

// 获取全部的角色列表
const getRolesList = async () => {
	try {
		const data = await role.roleListAllApi()
		formOptions.value.forms[7].options = data.map(item => {
			return { value: item.id, label: item.name }
		})
	} catch (e) {
		console.log(e)
	}
}

// 获取全部的部门列表
const getDepartmentsList = async () => {
	try {
		const data = await department.departmentListAllApi()
		formOptions.value.forms[8].options = data.map(item => {
			return { value: item.id, label: item.name }
		})
	} catch (e) {
		console.log(e)
	}
}

// 左侧菜单点击
const roleClick = data => {
	console.log(data.id, 'data.id')
	// 修改search参数 watch 变更 自动刷新 列表
	// searchData.value = { ...searchData.value, data: { roleId: data.id ? data.id : null } }
	searchData.value = { ...searchData.value, roleId: data.id || null }
}

// 表格搜索条件
const forms = ref([
	{
		prop: 'name',
		label: '账号/姓名：',
		itemType: 'input',
		placeholder: '请输入登录账号 / 姓名'
	},
	{
		prop: 'status',
		label: '状态：',
		itemType: 'select',
		placeholder: '请选择状态',
		options: [
			{
				label: '禁用',
				value: 0
			},
			{
				label: '正常',
				value: 1
			}
		]
	}
])

// table列表数据请求
const queryList = async () => {
	const { options, searchParams } = tableOpts
	options.loading = true
	console.log('搜索参数： ', JSON.stringify(tableOpts.searchParams))
	try {
		const { records: list, total } = await user.userPageApi(searchParams)
		tableOpts.total = total
		tableOpts.list = list
	} catch {
		console.log('获取列表数据失败')
		tableOpts.total = 0
		tableOpts.list = []
		options.loading = false // 更改加载中的 loading值
	} finally {
		options.loading = false
	}
}

// table 参数
const columns = [
	{
		prop: 'filterAvatar',
		label: '头像',
		minWidth: 80,
		slots: {
			default: 'filterAvatarSlot'
		}
	},
	{
		prop: 'username',
		label: '登录账号',
		minWidth: 100
	},
	{
		prop: 'status',
		label: '状态',
		minWidth: 60,
		slots: {
			default: 'statusSlot'
		}
	},
	{
		prop: 'nickName',
		label: '昵称',
		minWidth: 100
	},
	{
		prop: 'realName',
		label: '姓名',
		minWidth: 100
	},
	{
		prop: 'sex',
		label: '性别',
		minWidth: 80
	},
	{
		prop: 'updateBy',
		label: '修改人',
		minWidth: 100
	},
	{
		prop: 'updateTime',
		label: '修改时间',
		minWidth: 150
	},
	{
		prop: 'createBy',
		label: '创建人',
		minWidth: 100
	},
	{
		prop: 'createTime',
		label: '创建时间',
		minWidth: 150
	},
	{
		prop: 'action',
		label: '操作',
		width: 100,
		align: 'center',
		fixed: 'right',
		slots: {
			default: 'actionSlot'
		}
	}
]

const { searchData, tableOpts, checkedColumns, activeColumns, curSelectionRows, updateParams } = useTablePage(
	{
		options: {
			showIndex: false
		},
		// 需要展示的列
		columns,
		// 控制列配置
		columnsConfig: {
			columns
		}
	},
	{
		queryList,
		fetchImmediate: false
	}
)

// 删除
const deleteItem = async ids => {
	// try {
	await user.userDeleteApi(ids)
	ElMessage.success(`删除成功~`)
	updateParams()
	// } catch (e) {
	// 	console.log('删除失败')
	// 	ElMessage.error(`删除失败~`)
	// }
}

// 单个删除
const table_del = (row: any) => {
	ElMessageBox.confirm(`确认删除「${row.username}」这条数据？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'error'
	}).then(async () => {
		deleteItem([row.id])
	})
}

//批量删除
const batch_del = () => {
	const ids = curSelectionRows.value.map(item => item.id) // 多选数据
	ElMessageBox.confirm('是否删除选中数据？', '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'error',
		buttonSize: 'default'
	}).then(() => {
		deleteItem(ids)
	})
}

const table_edit = async row => {
	try {
		const data = await user.userRoleIdsApi({ id: row.id })
		isCreate.value = false
		activeData.value = { ...row, status: row.status ? true : false, roleIds: data?.roleIds, departmentIds: data?.departmentIds }
		visible.value = true
	} catch (e) {
		ElMessage.error(`获取用户所属角色失败~`)
	}
}

// 弹窗事件
const submitHandler = async params => {
	formOptions.value.formConfig.submitLoading = true
	try {
		params.status = params.status ? 1 : 0
		params.id = activeData.value.id ? activeData.value.id : null
		await user.userAddOrEditSaveApi(params)
		ElMessage.success(`${isCreate.value ? '新增' : '修改'}成功~`)
		visible.value = false
		updateParams()
		formOptions.value.formConfig.submitLoading = false
	} catch (e) {
		console.log(e)
		formOptions.value.formConfig.submitLoading = false
	}
}

const addHandler = () => {
	isCreate.value = true
	activeData.value = {}
	visible.value = true
}

const chooseThing = item => {
	assignRoleVisibile.value = true
	typeModel.value = item
}

nextTick(() => {
	getGroup()
	getRolesList()
	getDepartmentsList()
	queryList()
})

watch(groupFilterText, val => {
	treeRef.value!.filter(val)
})
</script>
<style scoped lang="scss">
.nopadding {
	padding: 0px;
}
</style>
